package com.wstuo.common.customForm.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.StringUtils;

import com.wstuo.common.customForm.dto.FormCustomQueryDTO;
import com.wstuo.common.customForm.entity.FormCustom;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.util.DaoUtils;

/**
 * 自定义表单模块DAO类
 * 
 * @author Wstuo
 * 
 */
public class FormCustomDAO extends BaseDAOImplHibernate<FormCustom> implements
		IFormCustomDAO {

	@Override
	public PageDTO findPager(FormCustomQueryDTO queryDto, String sord,
			String sidx) {
		DetachedCriteria dc = DetachedCriteria.forClass(FormCustom.class);
		int start = 0;
		int limit = 0;
		if (queryDto != null) {
			start = queryDto.getStart();
			limit = queryDto.getLimit();
			if (StringUtils.hasText(queryDto.getFormCustomName())) {// 标题
				dc.add(Restrictions.ilike("formCustomName",
						queryDto.getFormCustomName(), MatchMode.ANYWHERE));
			}
			if(queryDto.getCiCategoryNo()!=null&&queryDto.getCiCategoryNo()!=0){
				dc.add(Restrictions.eq("ciCategoryNo", queryDto.getCiCategoryNo()));
			}
			if(StringUtils.hasText(queryDto.getType())){
				dc.add(Restrictions.eq("type", queryDto.getType()));
			}
		}
		// 排序
		dc = DaoUtils.orderBy(sidx, sord, dc);
		return super.findPageByCriteria(dc, start, limit);
	}

	@SuppressWarnings("unchecked")
	public FormCustom findFormCustom(FormCustomQueryDTO queryDto) {
		FormCustom formCustom = new FormCustom();
		DetachedCriteria dc = DetachedCriteria.forClass(FormCustom.class);
		List<FormCustom> list = getHibernateTemplate().findByCriteria(dc);
		if (list != null && list.size() > 0) {
			formCustom = list.get(0);
		}
		return formCustom;

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FormCustom> findSimilarFormCustom(FormCustomQueryDTO queryDto) {
		DetachedCriteria dc = DetachedCriteria.forClass(FormCustom.class);
		List<FormCustom> list = new ArrayList<FormCustom>();
		if(StringUtils.hasText(queryDto.getType())){
			dc.add(Restrictions.eq("type", queryDto.getType()));
		}
		list = getHibernateTemplate().findByCriteria(dc);
		return list;
	}
	/**
	 * 是否存在相同表单名
	 * @param dto
	 * @return
	 */
	public Boolean isFormCustomNameExisted(FormCustomQueryDTO dto){
		DetachedCriteria dc = DetachedCriteria.forClass(FormCustom.class);
		dc.add(Restrictions.eq("formCustomName", dto.getFormCustomName()));
		dc.add(Restrictions.eq("type", dto.getType()));
		List<FormCustom> formCustom = getHibernateTemplate().findByCriteria(dc);
		return formCustom.isEmpty();
	}

}
